<?php

namespace app\api\model;

use app\api\controller\AddJob;
use app\api\controller\QueryInventory;
use app\api\controller\Shop;
use think\Model;

use app\api\model\Token;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * 合同评审模型
 */
class User extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';
 
    // 开启自动写入时间戳字段
    protected $auto_timestamp = 'false';
    
    
    public function phone_loginasd()
    {
       file_put_contents('v123.log', date('Y-m-d H:i:s', time()) . '执行了一次定时任务' . PHP_EOL, FILE_APPEND);
        
    }

    /*
    *请求金蝶即时库存登录接口
    */
    public function real_login(){
        //获取金蝶的即时库存数据
        $rse = $this->real_time_inventory_login();
        file_put_contents('create_inventory.log', date('Y-m-d H:i:s').':获取金蝶的即时库存数据结果'.json_encode($rse).PHP_EOL, FILE_APPEND);
        $query_inventory = Db::name("query_inventory")->order("id desc")->field("id,dataId")->select()->toArray();
        $rst = [];
        $flag = [];
        if(empty($query_inventory)){
            //金蝶返回数据，同步至crm
            // foreach($rse["data"] as $k=>$v){
            //     $rst[] = $this->create_inventory($rse["data"][$k]);
            file_put_contents('create_inventory.log', date('Y-m-d H:i:s').':即时库存开始同步数据'.PHP_EOL, FILE_APPEND);
            // }
            $pushJob = new AddJob();
            $pushJob->push($rse["data"]);
        }else{
            //62c6a3e118ff9c0001991f8d
            //数据存在，先删除数据
            // foreach($query_inventory as $k=>$v){
            //     $flag[] = $this->del_inventory($v["dataId"]);
            //     file_put_contents('create_inventory.log', date('Y-m-d H:i:s').':即时库存数据删除结果'.json_encode($flag).PHP_EOL, FILE_APPEND);
            // }
            Db::name('query_inventory')->field("id,dataId")->chunk(50, function($users) {
                foreach ($users as $user) {
                    $flag[] = $this->del_inventory($user["dataId"]);
                    file_put_contents('create_inventory.log', date('Y-m-d H:i:s').':即时库存数据删除结果'.json_encode($flag).PHP_EOL, FILE_APPEND);
                }
            });
            //删除成功之后重新同步
            // foreach($rse["data"] as $k1=>$v1){
            //     $rst[] = $this->create_inventory($rse["data"][$k1]);
            file_put_contents('create_inventory.log', date('Y-m-d H:i:s').':即时库存数据删除后同步数据'.PHP_EOL, FILE_APPEND);
            // }
            $pushJob = new AddJob();
            $pushJob->push($rse["data"]);

        }
        $this->success("同步成功");
    }

     //即时库存登录接口
     public function real_time_inventory_login(){
        libxml_disable_entity_loader(false);
        $client = new \SoapClient("http://10.108.0.57:8888/ormrpc/services/EASLogin?wsdl");//登录
       // $client = new \SoapClient("http://10.108.0.52:6888/ormrpc/services/EASLogin?wsdl");//登录
        $getFunctions = $client->__getFunctions(); //获取服务器上提供的方法
    
        $WSContext = $this->place_sub($getFunctions[3]);
        $substr = explode(",",$WSContext);
        $substr = count($substr);

        if($substr == 6){
             //6个参数
             $res = $client->login("blqjkNew","blqjk123","eas","A02","L2",2);
        }elseif($substr == 7){
             //7个参数
             $res = $client->login("blqjkNew","blqjk123","eas","server","L2",2,"BaseDB");
        }elseif($substr == 8){
             //8个参数
             $res = $client->login("blqjkNew","blqjk123","eas","server","L2",2,"BaseDB",0);
        }
        if(!empty($res->sessionId)){
            $row = $this->queryInventory($res->sessionId);
            if($row['msg']["result"] == "success"){
                $wrq = [
                    "code" =>1,
                    'msg'=>"成功",
                    'data'=>$row['msg']["inventory"]
                ];
            }else{
                $wrq = [
                    "code" =>0,
                    'msg'=>"失败",
                    'data'=>""
                ];
            }
            return $wrq;
        }else{
            $wrq = [
                "code" =>0,
                'msg'=>"失败",
                'data'=>$res
            ];
            return $wrq;
        }
    }

    //获取即时库存数据
    public function queryInventory($SessionId){
        libxml_disable_entity_loader(false);
        $client = new \SoapClient("http://10.108.0.57:8888/ormrpc/services/WSContractReviewFacade?wsdl");
        $jskc_data = [
            "isInit"=>true,
            "materialNums"=>[]
        ];
       $jskc_data = json_encode($jskc_data);
         //设置header格式
         $headerVar = new \SoapVar('<ns1:SessionId xmlns:ns1="http://login.webservice.bos.kingdee.com">'.$SessionId.'</ns1:SessionId>',XSD_ANYXML);
        
         //设置header值
         $header = new \SoapHeader('http://10.108.0.57:8888/ormrpc/services/WSContractReviewFacade?wsdl', 'queryInventory',$headerVar);
         $client->__setSoapHeaders(array($header));
         $jskc_data = [
             "isInit"=>true,
             "materialNums"=>[]
         ];
         $jskc_data = json_encode($jskc_data);
         //请求接口
         $res = $client->queryInventory($jskc_data);
         $inventory = json_decode($res,true);
         $ars = [
             'msg'=>$inventory
         ];
         return $ars;
    }

    public function place_sub($str) 
    { 
        $result = array(); 
        preg_match_all("/(?:\()(.*)(?:\))/i",$str, $result); 
        return $result[1][0]; 
    }

     /**
     * 获取token
     */
    public function corpAccessToken()
    {
        $method = 'POST';
        $appId = 'FSAID_131aba6';
        $appSecret = '69a6c56e23234bc9b56992f1468d103a';
        $permanentCode = 'F7BE99269E4BFC33400A92D039A3E28F';
        $url = 'https://open.fxiaoke.com/cgi/corpAccessToken/get/V2';
        $header = [
                         'Content-Type:application/json'
                   ];
        $res =  json_encode(compact('appId', 'appSecret', 'permanentCode'));
        $data = $this->http_curl($url,$method, $res, $header, $timeout = 10); 
        
        if(!empty($data) && isset($data) && $data['errorCode'] ==0 && $data['errorMessage'] == 'success' )
        {
            $data['addtime'] = time();
            if(Db::name('atoken')->where('id',1)->find())
            {
               $zxc = Db::name('atoken')->where('id',1)->update($data);  
            }else{
               $zxc = Db::name('atoken')->insert($data);  
            }
           return $data;
        }
        
    }
    /**
    * EAS即时库存同步到CRM
    */
    public function create_inventory($inventory_data)
    {
     
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/create';  // 创建客户对象 
       // owner 18394181267   220699002 合同评审编码 客户 特变电工山东鲁能泰山电缆有限公司
      
        $param['owner'] = "代冬冬";//$inventory_data["wareHousePerson"]
        $flag = $this->getByNickName($param['owner']);//通过员工昵称查询员工
        if($flag["code"] == 1){
            $owner_id = [$flag["data"]];
        }else{
            $this->error($flag["msg"]);
        }

        if($inventory_data["wareHouse"] == "自制监测器"){
            $inventory_data["wareHouse"] = "CRga2a684";
        }elseif($inventory_data["wareHouse"] == "成品库"){
            $inventory_data["wareHouse"] = "bpvRnt4Jh";
        }elseif($inventory_data["wareHouse"] == "监测器库"){
            $inventory_data["wareHouse"] = "oEH1o869g";
        }elseif($inventory_data["wareHouse"] == "外购成品库"){
            $inventory_data["wareHouse"] = "P13H7MS1p";
        }elseif($inventory_data["wareHouse"] == "绝缘类仓库"){
            $inventory_data["wareHouse"] = "7ojjfsaX7";
        }elseif($inventory_data["wareHouse"] == "复合附件库"){
            $inventory_data["wareHouse"] = "a9Zka42yG";
        }elseif($inventory_data["wareHouse"] == "瓷套库"){
            $inventory_data["wareHouse"] = "ZV9pEtC2y";
        }elseif($inventory_data["wareHouse"] == "自制电阻片"){
            $inventory_data["wareHouse"] = "x8w0d1u95";
        }elseif($inventory_data["wareHouse"] == "瓷壳附件库"){
            $inventory_data["wareHouse"] = "aNr521jjP";
        }elseif($inventory_data["wareHouse"] == "电器电材电机阀门库"){
            $inventory_data["wareHouse"] = "9pe1cwt8t";
        }elseif($inventory_data["wareHouse"] == "自制复合外套"){
            $inventory_data["wareHouse"] = "2ifAqDxeh";
        }elseif($inventory_data["wareHouse"] == "GIS附件库"){
            $inventory_data["wareHouse"] = "zh394Zpdc";
        }elseif($inventory_data["wareHouse"] == "外协类库"){
            $inventory_data["wareHouse"] = "i18OBD4kO";
        }elseif($inventory_data["wareHouse"] == "其他"){
            $inventory_data["wareHouse"] = "other";
        }else{
            $inventory_data["wareHouse"] = "";
        }
        $data = [];
        $data['object_data']["owner"] = $owner_id;
        $data['object_data']['field_718Re__c'] = $inventory_data["materialNum"];//产品编码
        //$data['object_data']['name'] = time();//产品编码
        $data['object_data']['field_VhiP2__c'] = $inventory_data["materialName"];//产品名称
        $data['object_data']['field_163T6__c'] = $inventory_data["unit"];//计量单位
        $data['object_data']['field_dw5E0__c'] = $inventory_data["model"];//规格型号
        $data['object_data']['field_0oe52__c'] = $inventory_data["assistProperty"];//辅助属性
        $data['object_data']['field_3hso4__c'] = $inventory_data["trackNumber"];//跟踪号
        $data['object_data']['field_Db7B2__c'] = $inventory_data["status"];//库存状态
        $data['object_data']['field_5sWyz__c'] = $inventory_data["curstoreQty"];//可用数量
        $data['object_data']['field_2833u__c'] = $inventory_data["baseUnit"];//基本计量单位
        $data['object_data']['field_1aSou__c'] = $inventory_data["baseQty"];//基本数量
        $data['object_data']['field_60J4D__c'] = $inventory_data["wareHouse"];//仓库
        $data['object_data']['dataObjectApiName'] = 'object_973mJ__c';

        //同步成功，数据添加到数据库
        $jskc_data = [
            "owner_name"=>$inventory_data["wareHousePerson"],
            "name"=>$inventory_data["materialNum"],
            "field_VhiP2__c" => $inventory_data["materialName"],//产品名称
            "field_163T6__c" => $inventory_data["unit"],//计量单位
            "field_dw5E0__c" => $inventory_data["model"],//规格型号
            "field_0oe52__c" => $inventory_data["assistProperty"],//辅助属性
            "field_3hso4__c" => $inventory_data["trackNumber"],//跟踪号
            "field_Db7B2__c" => $inventory_data["status"],//库存状态
            "field_5sWyz__c" => $inventory_data["curstoreQty"],//可用数量
            "field_2833u__c" => $inventory_data["baseUnit"],//基本计量单位
            "field_1aSou__c" => $inventory_data["baseQty"],//基本数量
            "field_60J4D__c" => $inventory_data["wareHouse"],//仓库
            "add_time"=>time()
        ];
        Db::name("query_inventory")->insert($jskc_data);
        $query_inventory_id = Db::name("query_inventory")->getLastInsID();
        $res = $this->qqtbff($data);
        $dsdf = $this->htcurl($url, json_encode($res));
       if($dsdf['errorMessage'] == 'OK'&& $dsdf['errorCode'] == 0)
       { 
            //62c6a3e118ff9c0001991f8d
            Db::name("query_inventory")->where("id",$query_inventory_id)->update(["status"=>2,"dataId"=>$dsdf["dataId"]]);
            file_put_contents('create_inventory.log', date('Y-m-d H:i:s').': 请求成功!即时库存数据已同步'.PHP_EOL, FILE_APPEND);
            return 1;
        }else{
            file_put_contents('create_inventory.log', date('Y-m-d H:i:s').':同步数据失败'.json_encode($dsdf).PHP_EOL, FILE_APPEND);
            return $this->error("同步数据失败");
        }
    }

     
     
        /**
        *  删除即时库存数据
        */
        protected function del_inventory($dataId)
        {
           $url = "https://open.fxiaoke.com/cgi/crm/custom/v2/data/delete";
           $qwe = $this->corpAccessToken();
           $corpAccessToken = $qwe['corpAccessToken'];   
           $corpId = $qwe['corpId'];
           $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';

           //作废自定义对象
           $sdgft = $this->invalid_inventory($dataId);
           if(!$sdgft){
              file_put_contents('create_inventory.log', date('Y-m-d H:i:s').':即时库存数据作废失败'.json_encode($sdgft).PHP_EOL, FILE_APPEND);
              return $this->error("作废数据失败"); 
           }
           
           $rst = [$dataId];
           $qwe = [
            "idList"=>$rst,
            'dataObjectApiName'=>"object_973mJ__c"
            ];
    
            $arr = [
                "corpAccessToken"=>$corpAccessToken,
                "corpId"=>$corpId,
                "currentOpenUserId"=>$currentOpenUserId,
                "data"=>$qwe,
            ];
            $res = json_encode($arr, JSON_UNESCAPED_UNICODE);
           
            $method = 'POST';
            $header = [
                        'Content-Type:application/json'
                    ];
            $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
            file_put_contents('create_inventory.log', date('Y-m-d H:i:s').':即时库存数据删除成功'.json_encode($dsdf).PHP_EOL, FILE_APPEND);
            if($dsdf['errorMessage'] == 'OK')
            {
                Db::name("query_inventory")->where("dataId",$dataId)->delete();
                return true; 
            }else{
                file_put_contents('create_inventory.log', date('Y-m-d H:i:s').': 请求结束，即时库存数据删除失败'.json_encode($dsdf['errorMessage']).PHP_EOL, FILE_APPEND);
                return  $this->error("删除数据失败");
            }
                
        }

        /**
        *  作废即时库存数据
        */
        protected function invalid_inventory($dataId)
        {
           $url = "https://open.fxiaoke.com/cgi/crm/custom/v2/data/invalid";
           $qwe = $this->corpAccessToken();
           $corpAccessToken = $qwe['corpAccessToken'];   
           $corpId = $qwe['corpId'];
           $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';

           $qwe = [
                "object_data_id"=>$dataId,
                'dataObjectApiName'=>"object_973mJ__c"
            ];
    
            $arr = [
                "corpAccessToken"=>$corpAccessToken,
                "corpId"=>$corpId,
                "currentOpenUserId"=>$currentOpenUserId,
                "data"=>$qwe,
            ];
            $res = json_encode($arr, JSON_UNESCAPED_UNICODE);
           
            $method = 'POST';
            $header = [
                        'Content-Type:application/json'
                    ];
            $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
            file_put_contents('create_inventory.log', date('Y-m-d H:i:s').':即时库存数据作废'.json_encode($dsdf).PHP_EOL, FILE_APPEND);
            if($dsdf['errorMessage'] == 'OK')
            {
                return true; 
            }else{
                file_put_contents('create_inventory.log', date('Y-m-d H:i:s').': 请求结束，即时库存数据作废失败'.json_encode($dsdf['errorMessage']).PHP_EOL, FILE_APPEND);
                return false; 
            }
                
        }
        

    //根据手机号获取crm用户id
    public function getByMobile($owner_id){
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/user/getByMobile';  // 根据手机号查询员工
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        //$mobile = "18394181267";
        $phone = explode(",",$owner_id);
        $sdf = [];
        foreach ($phone as $mobile){
            $res =  json_encode(compact('corpAccessToken', 'corpId', 'mobile'),JSON_UNESCAPED_UNICODE);
        
            $method = 'POST';
            $header = [
                            'Content-Type:application/json'
                        ];
            $dsdf = $this->http_curl($url,$method, $res, $header);
            if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'success' && !empty($dsdf['empList']) )
            {
            $sdf[] = $dsdf['empList'][0]["openUserId"];
            }
        }
        return $sdf;
    }

    //根据员工昵称获取crm用户id
    public function getByNickName($nickName){
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/user/getByNickName';  // 通过员工昵称查询员工
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        //$mobile = "刘兴堂";
        $phone = explode(",",$nickName);
        $sdf = [];
        foreach ($phone as $nickName){
            $res =  json_encode(compact('corpAccessToken', 'corpId', 'nickName'),JSON_UNESCAPED_UNICODE);
            $method = 'POST';
            $header = [
                            'Content-Type:application/json'
                        ];
            $dsdf = $this->http_curl($url,$method, $res, $header);
          
            if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'success' && !empty($dsdf['empList']) )
            {
            //$sdf[] = $dsdf['empList'][0]["openUserId"];
                $rst = [
                    "code"=>1,
                    "data"=>$dsdf['empList'][0]["openUserId"]

                ];
            }else{
                $rst = [
                    "code"=>-1,
                    "msg"=>$dsdf["errorDescription"]

                ];
            }
        }
        return $rst;
    }

    //轻流客户   根据负责人查出负责人邮箱
    public function get_onwer($owner){
        // $id = "18991274097";
         $qwe = $this->corpAccessToken();
         $url ='https://open.fxiaoke.com/cgi/crm/v2/data/query';  // 根据条件查询人员对象的列表 
         $corpAccessToken = $qwe['corpAccessToken'];   
         $corpId = $qwe['corpId'];
         $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
         $data = ['dataObjectApiName'=>'PersonnelObj','search_query_info'=>[ 'offset'=>0, 'limit'=>1, 'filters'=>[[ 'field_name'=>'phone','field_values'=>[$owner],'operator'=>'EQ' ]]]];
         $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        // dump($res);die;
         $method = 'POST';
          $header = [
                        'Content-Type:application/json'
                    ];
         $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
         if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorDescription'] == 'success' && $dsdf['errorMessage'] == 'OK')
          {
             return $dsdf["data"]["dataList"][0]["email"];
          }else{
             return false; 
          }
     }
    
    //查询关联合同评审
    public function contract_review($name){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/query';
       //   $url = 'https://open.fxiaoke.com/cgi/crm/v2/data/query ';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
        $data = [ 'search_query_info'=>[ 'offset'=>0, 'limit'=>100, 'filters'=>[[ 'field_name'=>'name','field_values'=>[$name],'operator'=>'EQ' ]]],'dataObjectApiName'=>'object_qdBZ2__c'];
 
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        //dump($res);die;
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0 &&  !empty($dsdf["data"]["dataList"])){
            return $dsdf["data"]["dataList"][0]["_id"];
        }else{
            return "";
        }
    }

    //查询关联客户
    public function gl_customer($name){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/findOne';
       //   $url = 'https://open.fxiaoke.com/cgi/crm/v2/data/query ';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
        $data = [ 'search_query_info'=>[ 'offset'=>0, 'limit'=>100, 'filters'=>[[ 'field_name'=>'name','field_values'=>[$name],'operator'=>'EQ' ]]],'dataObjectApiName'=>'AccountObj'];
 
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        //dump($res);die;
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0){
            return $dsdf["data"]["objectData"]["_id"];
        }else{
            return "";
        }
    }
       

    /**
       *   post 请求体 头部 封装
       */
      protected function qqtbff($data)
      {
         $qwe = $this->corpAccessToken();
         $corpAccessToken = $qwe['corpAccessToken'];   
         $corpId = $qwe['corpId'];
         $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
         $res =  compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data');
        //   dump($res);die; 
        return $res;
      }


          /**
     * 发送 post 请求 
     * @access protected
     * @return string
     */
  
    
 protected function htcurl($url, $data = array())
 {
      $method = 'POST';
      $timeout = 10;
      $header = [
                       'Content-Type:application/json'
                 ];
     $curl = curl_init($url);
     $method = strtoupper($method);
     //请求方式啥
     curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
     //post请求
     if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
     //超时时间
     curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
     //设置header头
     // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
     curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
     
     curl_setopt($curl, CURLOPT_FAILONERROR, false);
     //返回抓取数据
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
     //输出header头信息
     curl_setopt($curl, CURLOPT_HEADER, true);
     //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
     curl_setopt($curl, CURLINFO_HEADER_OUT, true);

     //https请求
     if (1 == strpos("$" . $url, "https://")) {
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
     }
     $curlError = curl_error($curl);
     list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
     $status = $status;
     $headerStr = trim(substr($content, 0, $status['header_size']));
     $content = trim(substr($content, $status['header_size']));
      
      $cont = json_decode($content,true);
      
     //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
      return $cont;

 }
  
   /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */
    protected function http_curl($url, $method = 'POST', $data = array(), $header, $timeout = 10)
   {
       $curl = curl_init($url);
       $method = strtoupper($method);
       //请求方式啥
       curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
       //post请求
       if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
       //超时时间
       curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
       //设置header头
       // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
       curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
       
       curl_setopt($curl, CURLOPT_FAILONERROR, false);
       //返回抓取数据
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       //输出header头信息
       curl_setopt($curl, CURLOPT_HEADER, true);
       //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
       curl_setopt($curl, CURLINFO_HEADER_OUT, true);

       //https请求
       if (1 == strpos("$" . $url, "https://")) {
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
       }
       $curlError = curl_error($curl);
       list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
       $status = $status;
       $headerStr = trim(substr($content, 0, $status['header_size']));
       $content = trim(substr($content, $status['header_size']));
        
        $cont = json_decode($content,true);
        
       //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
        return $cont;

   }
   
     
  
}
